(function($){ 

var chart;
var buttonValue;
var baseUrl = 'http://127.0.0.1:8081/?param=';
var plotLineOn = false;

$(document).ready(function() {	
	// callendar handling
	$("#endDate").datepicker(
	{
	onSelect: function()
	{ 
		var dateObject = $(this).datepicker('getDate'); 
		$("select").trigger('mouseup');
	}
	});
	
	$("#startDate").datepicker(
	{
	onSelect: function()
	{ 
		var dateObject = $(this).datepicker('getDate'); 
		$("select").trigger('mouseup');
	}
	});
	
	// handle change event 
	$("#startDate").change(function() { 
		$("select").trigger('mouseup');
	});
	$("#endDate").change(function() { 
		$("select").trigger('mouseup');
	});
	
	// timer select box handling
	$('#startHour').change(function() {
		var selectVal = $('#startHour :selected').val();
		$("select").trigger('mouseup');
	});

	$('#endHour').change(function() {
		var selectVal = $('#endHour :selected').val();
		$("select").trigger('mouseup');
	});
	
	// next
	$("#next").mouseup(function(){
		$('#selectAtt option:selected').next().attr('selected', 'selected');
		$("select").change();
	
	});
	
	// previous 
	$("#previous").mouseup(function(){
		$('#selectAtt option:selected').prev().attr('selected', 'selected');
		$("select").change();
	});
	
}); 



// select box handling
$(document).ready(function() {
$("select").mouseup(function () {
	  $("select option:selected").each(function () {				
			callUrl = baseUrl + document.getElementById('selectAtt').value;
			
			// getting date and hour
			var startDate = document.getElementById('startDate').value;			
			var endDate = document.getElementById('endDate').value;	
			var startHour = document.getElementById('startHour').value;			
			var endHour = document.getElementById('endHour').value;	
			callUrl += '&startDate=' +startDate+ '&endDate=' +endDate+ '&startHour=' +startHour+ '&endHour=' +endHour; 
			
			titleText = $("#selectAtt option:selected").text(); 
			requestData(callUrl);			
	  });		 
})
.trigger('change'); 
});


// getting data from given URLa
function requestData(callUrl) {	  
	$.ajax({
		dataType: "json",
		url: callUrl,
		type: "GET",
	}).done(function ( data ) {
		var items = [];						
		var series = chart.series[0];
		var noEvents = 0;
		var avgTime = 0;
		var procData = $.map(data, function(item){
			noEvents += 1;			
			avgTime += parseInt(item.yAxis, 10);			
			return [[parseInt(item.xAxis, 10), parseInt(item.yAxis, 10)]];          
		});
		procData.sort(function(a, b){
		 return a[0] - b[0];            
		});		
		
		// counting average time 
		avgTime = Math.round(avgTime/noEvents*1000)/1000;
		var optionLabel = $('#selectAtt :selected').parent().attr('label');
		if (optionLabel == "Navigation Timing Attributes") {
			document.getElementById('avgTime').innerHTML  = "";
		}
		else {
			document.getElementById('avgTime').innerHTML  = avgTime;
		}
		
		// setting number of events occured
		document.getElementById('noEvents').innerHTML  = noEvents;	
		chart.setTitle({text: titleText});
		
		// setting AVG Line On between requests
		$avgLineButton = $('#avgLineButton');  
		if (plotLineOn) {	
			chart.yAxis[0].removePlotLine('plot-line-1');
            chart.yAxis[0].addPlotLine({
                value: document.getElementById('avgTime').innerHTML,
                color: 'red',
                width: 2,
                id: 'plot-line-1',
				dashStyle : 'shortdash'
            });
            $avgLineButton.html('Remove AVG Line');
        }
		
		series.setData(procData);				
	});
};

// handling AVG Line Button
$(function () {	
	$avgLineButton = $('#avgLineButton');    
	var hasPlotLine = false;
		
    $avgLineButton.click(function() {
        if (!hasPlotLine) {	
			plotLineOn = true;
            chart.yAxis[0].addPlotLine({
                value: document.getElementById('avgTime').innerHTML,
                color: 'red',
                width: 2,
                id: 'plot-line-1',
				dashStyle : 'shortdash'
            });
            $avgLineButton.html('Remove AVG Line');
        } else {
			plotLineOn = false;
            chart.yAxis[0].removePlotLine('plot-line-1');
            $avgLineButton.html('Add Avg Line');			
        }
        hasPlotLine = !hasPlotLine;
    });
	
});

// handling Area Chart Button
$(function () {	
	$areaSubmit = $('#areaSubmit');    
		
    $areaSubmit.click(function() {
		chart.series[0].update({
			type: 'column'
		});
		chart.xAxis[0].update({
            type: 'category'
        });
    });
});

// attribute: Navigation Types handler
$(function () {	
	$("#selectAtt").change(function(){
		if ($("#selectAtt").val() == "navTypes") {		
		
			// changing types
			chart.series[0].update({
				type: 'column'
			});
			chart.xAxis[0].update({
				type: 'category',
				tickInterval: null
			});
		   
		   // changing tooltip formatter 
			chart.tooltip.options.formatter = function() {	
				return '<b>'+ this.series.name +'</b><br/>'+
				this.x +': '+ this.y;	
			}
			
			// changing yAxis title
			chart.yAxis[0].axisTitle.attr({
				text: 'Requests'
			});
			
			$("#table2").css("visibility","visible"); 
		}
		else {
			// changing types
			chart.series[0].update({
				type: 'line'
			});
			chart.xAxis[0].update({
				type: 'datetime',
				tickInterval: null
			});
		
		   // changing tooltip formatter 
			chart.tooltip.options.formatter = function() {						
				return '<b>'+ this.series.name +'</b><br/>'+
				this.x +': '+ this.y + ' ms';				
			}
			// changing yAxis title
			chart.yAxis[0].axisTitle.attr({
				text: 'Time [ms]'
			});
			chart.yAxis[0].update({
				type: null			
			});	
			$("#table2").css("visibility","hidden"); 
		}		

		var optionLabel = $('#selectAtt :selected').parent().attr('label');
		
		if (optionLabel == "Navigation Timing Attributes") {			
			chart.xAxis[0].update({
				type: 'category',
				tickInterval: 5
			});
			chart.yAxis[0].update({
				type: 'datetime'				
			});			
		}
		
	});	
});






$(document).ready(function() {
	
	chart = new Highcharts.Chart({
		chart: {
			renderTo: 'container',
			type: 'line',
			marginRight: 130,
			marginBottom: 25
		},
		title: {
			text: '',
			x: -20 //center
		},
		subtitle: {
			text: 'Source: Navigation Timing API',
			x: -20
		},
		xAxis: {
			type: 'datetime'
		},
		yAxis: {
			title: {
				text: 'Time [ms]'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'				
			}]
		},
		tooltip: {
			formatter: function() {
				return '<b>'+ this.series.name +'</b><br/>'+
				this.x +': '+ this.y +'ms';
			}
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'top',
			x: -10,
			y: 100,
			borderWidth: 0
		},
		series: [{ 
            name: 'Performance',
            data: []
        }]
	});
	
}); 

})(jQuery);
